package com.news.presenter;

import com.news.base.HttpResponse;
import com.news.base.RxPresenter;
import com.news.model.bean.Joke;
import com.news.model.http.RetrofitHelper;
import com.news.presenter.contract.JokeContract;
import com.news.util.LogUtil;

import java.util.ArrayList;

import javax.inject.Inject;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;

/**
 * Created by Administrator on 2017/3/1 0001.
 */

public class JokePresenter extends RxPresenter<JokeContract.View> implements JokeContract.Presenter {

    private RetrofitHelper mRetrofitHelper;

    @Inject
    JokePresenter(RetrofitHelper retrofitHelper) {
        this.mRetrofitHelper = retrofitHelper;
    }

    @Override
    public void fetchJokes() {
        if (isViewAttached()) {
            getView().showLoading();
        }
        Observable<HttpResponse<ArrayList<Joke>>> jokeObservable = mRetrofitHelper.fetchJokeImage();
        Subscription subscribe = jokeObservable
                .subscribe(new Subscriber<HttpResponse<ArrayList<Joke>>>() {
                    @Override
                    public void onCompleted() {
                        LogUtil.d("JokePresenter", "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d("JokePresenter", "onError: " + e.getMessage());
                        if (isViewAttached()){
                            getView().showError(e.getMessage());
                            getView().hideLoading();
                        }
                    }

                    @Override
                    public void onNext(HttpResponse<ArrayList<Joke>> httpResponse) {
                        LogUtil.d("JokePresenter", "onNext: " + httpResponse.toString());
                        if (isViewAttached()) {
                            getView().hideLoading();
                            getView().showJokes(httpResponse.getData());
                        }
                    }
                });
        addSubscribe(subscribe);
    }

}
